package com.go.where.family.component.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.go.where.family.component.FamilySquareComponent;
import com.go.where.family.constants.Constant;
import com.go.where.family.constants.TransmissionCode;
import com.go.where.family.exception.ServerDisponseException;
import com.go.where.family.jersey.api.EasemobMessages;
import com.go.where.family.pojo.CustomerAttentionInfo;
import com.go.where.family.pojo.CustomerInfo;
import com.go.where.family.pojo.FamilySquareInfo;
import com.go.where.family.scoket.Head;
import com.go.where.family.service.CustomerAttentionService;
import com.go.where.family.service.CustomerService;
import com.go.where.family.service.FamilySquareService;
import com.go.where.family.utils.CommonUtil;
import com.go.where.family.vo.EasemobVo;
import com.go.where.family.vo.FamilySquareVo;
import com.google.gson.Gson;

@Component("familySquareComponent")
public class FamilySquareComponentImpl implements FamilySquareComponent {

	private static final Logger log = Logger
			.getLogger(FamilySquareComponentImpl.class);
	private Gson gson;
	@Resource(name = "familySquareService")
	private FamilySquareService familySquareService;
	@Resource(name = "customerAttentionService")
	private CustomerAttentionService customerAttentionService;
	@Resource
	private CustomerService customerService;

	public FamilySquareComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public List<FamilySquareInfo> queryList(String body, Head head) {
		FamilySquareVo vo = gson.fromJson(body, FamilySquareVo.class);
		if (vo != null) {
			Integer currentPage = vo.getPageIndex();
			Integer pageSize = vo.getPageCount();
			Integer pageStart = 1;
			Integer pageEnd = 10;
			if (currentPage != null && pageSize != null) {
				pageStart = (currentPage - 1) * pageSize + 1;
				pageEnd = currentPage * pageSize;
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("pageStart", pageStart);
			map.put("pageEnd", pageEnd);
			map.put("isDelete", Constant.IS_NOT_DELETE);
			map.put("content", vo.getContent());
			if (StringUtils.isNotBlank(vo.getViewCustomerId())) {
				map.put("customerId", vo.getViewCustomerId());
			}
			if (StringUtils.isNotBlank(vo.getOrderBy())) {
				if (Constant.ORDER_TYPE_ASC.equals(vo.getOrderType())) {
					map.put("page_orderByAsc", vo.getOrderBy());
				} else {
					map.put("page_orderByDesc", vo.getOrderBy());
				}
			}

			List<FamilySquareInfo> list = familySquareService.queryList(map);
			if (list != null && !list.isEmpty()) {
				for (FamilySquareInfo square : list) {
					if (StringUtils.isNotBlank(square.getHeaderPath())) {
						square.setHeaderPath(CommonUtil.getUrlPrefix()
								+ square.getHeaderPath());
					}
					if (StringUtils.isNotBlank(square.getPhotoPath())) {
						String[] phs = square.getPhotoPath().split(";");
						List<String> photos = new ArrayList<String>();
						for (String ph : phs) {
							if (StringUtils.isNotBlank(ph)) {
								photos.add(CommonUtil.getUrlPrefix() + ph);
							}
						}
						square.setPhotos(photos);
					}
					CustomerAttentionInfo cai = new CustomerAttentionInfo();
					cai.setFollowedId(square.getCustomerId());
					if (StringUtils.isNotBlank(vo.getViewCustomerId())) {
						cai.setCustomerId(vo.getViewCustomerId());
					} else {
						cai.setCustomerId(vo.getCustomerId());
					}
					CustomerAttentionInfo att = customerAttentionService
							.queryParameter(cai);
					if (att != null) {
						square.setIsAttention(true);
					} else {
						square.setIsAttention(false);
					}
				}
				return list;
			} else {
				return new ArrayList<FamilySquareInfo>();
			}
		} else {
			log.info("requestId:" + head.getRequestId()
					+ ",获取家族广场列表信息时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public boolean updateLike(String body, Head head) {
		FamilySquareVo vo = gson.fromJson(body, FamilySquareVo.class);
		if (vo != null) {
			String id = vo.getId();
			FamilySquareInfo ti = familySquareService.queryDetailSquare(id);
			if (ti != null) {
				Integer likeNum = ti.getLikeNum();
				if ("1".equals(vo.getLikeOrNot())) {
					likeNum = CommonUtil.add(likeNum, 1);
				} else if ("0".equals(vo.getLikeOrNot())) {
					likeNum = CommonUtil.sub(likeNum, 1);
				}
				FamilySquareInfo ff = new FamilySquareInfo();
				ff.setId(id);
				ff.setLikeNum(likeNum);
				int re = familySquareService.update(ff);
				if (re > 0) {
					if ("1".equals(vo.getLikeOrNot())
							&& !vo.getCustomerId().equals(ti.getCustomerId())) {
						sendMsg(head, ti.getCustomerId(), vo,
								Constant.MESSAGE_TYPE_SQUARE_LIKE);
					}
					return true;
				} else {
					return false;
				}
			} else {
				log.info("requestId:" + head.getRequestId()
						+ ",更新家族广场点赞量时,没有查询到数据,广场ID：" + id);
				throw new ServerDisponseException(TransmissionCode.NO_DATA
						.getCode(), TransmissionCode.NO_DATA.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",更新课题点赞量，报文解析异常");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	private void sendMsg(Head head, String squCustomerId, FamilySquareVo vo,
			int messageType) {
		List<String> customerIdList = new ArrayList<String>();
		if (Constant.MESSAGE_TYPE_SQUARE_LIKE == messageType) {
			if (StringUtils.isNotBlank(squCustomerId)) {
				customerIdList.add(squCustomerId);
			}
		} else {
			CustomerAttentionInfo attInfo = new CustomerAttentionInfo();
			attInfo.setFollowedId(vo.getCustomerId());
			customerIdList = this.customerAttentionService
					.queryByFollowed(attInfo);
		}
		CustomerInfo ci = customerService.queryByPrimaryKey(vo.getCustomerId(),
				head);
		String customerNick = ci.getCustomerNick();
		if (StringUtils.isBlank(customerNick)) {
			customerNick = ci.getCustomerId();
		}
		if (customerIdList != null && !customerIdList.isEmpty()) {
			EasemobVo easemobVo = new EasemobVo();
			easemobVo.setUserId(ci.getCustomerId());
			easemobVo.setUserName(customerNick);
			easemobVo.setMessageType(messageType);
			easemobVo.setMessageTime(new Date());
			List<String> failedUserId = EasemobMessages.sendMessages(vo
					.getCustomerId(), customerIdList, gson.toJson(easemobVo));
			if (failedUserId != null && !failedUserId.isEmpty()) {
				log.info("requestId:" + head.getRequestId()
						+ ",发布广场信息或广场点赞时，发送消息的失败用户ID："
						+ failedUserId.toString());
			} else {
				log.info("requestId:" + head.getRequestId()
						+ "发布广场信息或广场点赞，消息推送成功,用户列表：" + customerIdList);
			}
		}
	}

	@Override
	public boolean save(String body, Head head) {
		FamilySquareVo vo = gson.fromJson(body, FamilySquareVo.class);
		if (vo != null) {
			FamilySquareInfo ff = new FamilySquareInfo();
			ff.setTitle(vo.getTitle());
			ff.setContent(vo.getContent());
			ff.setCustomerId(vo.getCustomerId());
			ff.setPhotoPath(vo.getPhotoPath());
			int re = familySquareService.save(ff);
			if (re > 0) {
				sendMsg(head, "", vo, Constant.MESSAGE_TYPE_PUBLISH_SQUARE);
				return true;
			} else {
				return false;
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",保存家族广场信息时，报文解析异常");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

	@Override
	public boolean delete(String body, Head head) {
		FamilySquareVo vo = gson.fromJson(body, FamilySquareVo.class);
		if (vo != null) {
			FamilySquareInfo ff = new FamilySquareInfo();
			ff.setId(vo.getId());
			ff.setCustomerId(vo.getCustomerId());
			ff.setIsDelete(Constant.IS_DELETE);
			int re = familySquareService.update(ff);
			if (re > 0) {
				return true;
			} else {
				return false;
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",删除家族广场信息时，报文解析异常");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}
}
